// import { from } from "core-js/core/array"
import {getToken,setToken,removeToken} from '@/utils/auth'
import { getProfile,getUserByIdDetail,login } from '@/api/user'
export default{
  //放入核心代码
  namespaced: true,
  state:{
    //优先本地存储获取数据
    token:getToken()||''//存储token
  },
  //数据同步更新的地方
  mutations:{
    updateToken(state,token){
      state.token=token
      //将token存储到本存储显示持久化
      setToken(token)
    },
    delToken(state){
      state.token=''
      //清空cookies中的token
      removeToken()
    },
    updateUserInfo(state, info) {
      state.userInfo = info
    },
    delUerInfo(state) {
      state.userInfo = {}
    }
  },
  delUerInfo(state){
    state.userInfo={}
  },
  //数据异步更新
actions:{ 
  async initToken(context,formData){
    const res =await login(formData)
    console.log(res,'res');
    if(res.code!=10000) return Message.error(res.message)
    Message.success(res.message)
    context.commit('updateToken',res.data);
  },
   // 定义函数发送请求.获取用户信息,存储vue
  async getUserInfo(context) {
    // context是Store的实例,context.commit()
    // console.log(context, 'cotext')
    try {
      const res = await getProfile()
      console.log(res, 'getUserProfile')
      const info = await getUserByIdDetail(res.data.userId)
      console.log(info, 'getUserByIdDetail')
      context.commit('updateUserInfo', { ...res.data, ...info.data })
    } catch (error) {
      console.log(error)
    }
  },
  logout(context) {
    context.commit('delToken')
    context.commit('delUerInfo')
  }}
}